#!/usr/bin/env python
#coding=utf-8

import re
import os
import time
import logging
import types
import socket
import datetime as dt
from datetime import datetime, timedelta, date

from xsl import XLSWriter
from vic.exchange.vic_huobi.huobi_http import HuobiHttp
from vic.exchange.vic_okex.okex_http import OkexHttp
from vic.exchange.vic_binance.binance_http import BinaHttp
from vic.exchange.vic_okex.okexft_http import OkexftHttp

def bina_http(url, apiKey, apiSecret):
    bina  = BinaHttp(url, apiKey, apiSecret)
    return bina

def huobi_http(url, apiKey, apiSecret):
    huobi  = HuobiHttp(url, apiKey, apiSecret)
    return huobi

def okex_http(url, apiKey, apiSecret):
    okex  = OkexHttp(url, apiKey, apiSecret)
    return okex

def log_info(logtext):
    logger = logging.getLogger()
    logger.info(logtext)


def log_error(logtext):
    logger = logging.getLogger()
    logger.error(logtext)


def log_debug(logtext):
    logger = logging.getLogger()
    logger.debug(logtext)


def log_exception(logtext):
    logger = logging.getLogger()
    logger.exception(logtext)


def list_add(a, b):
    """列表相加"""
    new_list=[a[i]+b[i] for i in range(min(len(a),len(b)))]
    return new_list


def list_multiply(a, b):
    new_list=[a[i]*b[i] for i in range(min(len(a),len(b)))]
    return new_list


def str2timestamp(str_date, format_style="%Y-%m-%d", zone=None):
    """@param:     str_date: string, 时间
       @param:     format_style: string, '%Y-%m-%d %H:%M:%S'
       @return:    int, 转换出错默认返回0
    """
    timeArray = time.strptime(str_date, format_style)
    if zone:
        tz = timezone(zone)
        y,m,d,H,M,S = timeArray[0:6]
        dt = datetime(y,m,d,H,M,S)
        t = tz.localize(dt)
        t = t.astimezone(pytz.utc)
        return int(time.mktime(t.utctimetuple()))-time.timezone
    return int(time.mktime(timeArray))


def before_after_timestamp(timestamp, days=0):
    """ 获取今天前后X天的0点00分00秒的时间戳 """
    """ days: 正整数为未来, 负整数为过去 """

    _datetime = datetime.utcfromtimestamp(timestamp)
    day       = _datetime + timedelta(days=days, hours=8)
    day_str   = day.strftime("%Y-%m-%d")
    timestamp = str2timestamp(day_str, "%Y-%m-%d")

    return timestamp


def timestamp2str(timestamp, format_style="%Y-%m-%d"):
    """ 时间戳转换为指定格式时间 """

    time_array = time.localtime(timestamp)
    return time.strftime(format_style, time_array)


def current_strtime(format_style="%Y-%m-%d %H:%M:%S"):
    """ 获取当前时间 """

    now = datetime.now()
    return now.strftime(format_style)



def format_timestamp(timestamp, format='%Y-%m-%d %H:%M:%S'):

    if timestamp is None or not timestamp:
        return ''

    if type(timestamp) in (types.StringType, types.UnicodeType):
        return timestamp

    if format is 'isodate':
        format = '%Y-%m-%d %H:%M:%S'
    elif format in ('date', 'shortdate', 'short-date'):
                format = '%Y-%m-%d'
    elif format is 'time':
                format = '%H:%M:%S'

    try:
        date_time = dt.datetime.fromtimestamp(timestamp).strftime(format)
    except Exception as e:
        date_time = dt.datetime(1970, 1, 1) + datetime.timedelta(seconds=timestamp)

    return date_time



def excel_folder_path():
    """excel文件目录"""

    target_folder = './data/' + str(date.today())
    if not os.path.exists(target_folder):
        os.makedirs(target_folder)

    return target_folder


def config_data():
    """配置文件路径"""

    _data = {}

    ip = localip()
    file = "../conf/config.txt" if ip == '47.74.179.216' else "../conf/config_test.txt"
    #file = "../conf/config.txt"
    with open(file, 'r') as f:
        data = f.read()
        data      = data.replace('\r', '')
        data_list = data.split('\n')
        for d in data_list:
            d_list = re.split(r'[\s\,]+', d)
            if not d_list[0]:
                continue # 如果没有获取到键，就循环下一个
            key    = d_list[0]
            value  = d_list[2]
            _data[key] = value

    return _data


def get_symbol(currency, to_currency, trading):
    # symbol处理
    currency    = currency.lower()
    to_currency = to_currency.lower()

    if trading == 'okex':
        symbol = '%s_%s' %(currency, to_currency)
    elif trading == 'bina':
        currency    = currency.upper()
        to_currency = to_currency.upper()
        symbol = '%s%s' %(currency, to_currency)
    else:
        symbol = '%s%s' %(currency, to_currency)
    return symbol

def config_error_code_msg(code, file):
    """读取配置文件的错误码对应的信息"""
    msg = ''
    with open(file, 'r') as f:
        data      = f.read()
        data      = data.replace('\r', '')
        data_list = data.split('\n')
        for d in data_list:
            d_list = re.split(r'[\s\,]+', d)
            if not d_list[0]:
                continue # 如果没有获取到键，就循环下一个

            code = '%s' % code
            if d_list[0] == code:
                msg = d_list[1]

    return msg



def localip():
    """获取本地ip"""

    import socket
    #获取本机电脑名
    myname = socket.getfqdn(socket.gethostname(  ))
    #获取本机ip
    myaddr = socket.gethostbyname(myname)

    return myaddr
